package com.example.archive.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.elasticsearch.client.RestHighLevelClient;

/**
 * Elasticsearch配置类
 * 配置Elasticsearch连接和客户端
 * 适配Spring Boot 2.7.18版本
 */
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.example.archive.repository.elasticsearch")
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
    
    @Value("${spring.elasticsearch.uris:http://localhost:9200}")
    private String elasticsearchUrl;
    
    @Value("${spring.elasticsearch.username:}")
    private String username;
    
    @Value("${spring.elasticsearch.password:}")
    private String password;
    
    @Override
    public RestHighLevelClient elasticsearchClient() {
        // 移除协议前缀，只保留主机和端口
        String hostAndPort = elasticsearchUrl.replace("http://", "").replace("https://", "");
        
        // 构建客户端配置
        ClientConfiguration clientConfiguration;
        
        // 如果配置了用户名和密码，则添加认证
        if (username != null && !username.isEmpty() && 
            password != null && !password.isEmpty()) {
            clientConfiguration = ClientConfiguration.builder()
                .connectedTo(hostAndPort)
                .withBasicAuth(username, password)
                .withConnectTimeout(java.time.Duration.ofSeconds(10))
                .withSocketTimeout(java.time.Duration.ofSeconds(30))
                .build();
        } else {
            // 无认证配置
            clientConfiguration = ClientConfiguration.builder()
                .connectedTo(hostAndPort)
                .withConnectTimeout(java.time.Duration.ofSeconds(10))
                .withSocketTimeout(java.time.Duration.ofSeconds(30))
                .build();
        }
        
        return RestClients.create(clientConfiguration).rest();
    }
} 